package ca.llsutherland.nfl.dao;

import java.sql.ResultSet;
import java.sql.SQLException;

import ca.llsutherland.nfl.domain.WeekType;
import ca.llsutherland.nfl.exception.ValidationException;
import ca.llsutherland.nfl.helper.WeekTypeHelper;
import ca.llsutherland.nfl.util.StringUtil;

public class WeekTypeDao extends BaseDao {

	   private static WeekTypeDao instance = new WeekTypeDao();

	    @Override
	    public String getUnderlyingTableName() {
	        return "WEEK_TYPE";
	    }

	    public static WeekTypeDao getInstance() {
	        return instance ;
	    }

	    public WeekType findByName(String name) {
	        String findByNameQuery = getFindByNameQuery(name);
	        return buildWeekType(findByNameQuery);
	    }

	    private WeekType buildWeekType(String sql) {
	        WeekType weekType = null;
	        ResultSet rs = super.findByQuery(sql);
	        
	        try {
	            if(rs.next()){
	            	weekType = WeekTypeHelper.createNewWeekType(Long.valueOf(rs.getLong("ID")), rs.getString("NAME"));
	            }
	            rs.close();
	        } catch (SQLException e) {
	            throw new ValidationException(e.getMessage() + " in buildWeekType()");
	        } finally {
	            rs = null;            
	        }
	        return weekType;
	    }

	    public WeekType create(WeekType weekType) {
	        String sql = "INSERT INTO " + getUnderlyingTableName() + " (NAME) VALUES (" + StringUtil.addSingleQuotes(weekType.getName()) + ");";
	        return findById(super.create(sql));
	    }

	    public WeekType findById(Long id) {
	        String findByIdQuery = getFindByIdQuery(id);
	        return buildWeekType(findByIdQuery);
	    }


}
